package com.ft.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ft.dao.StudyAnswerDao;
import com.ft.dao.StudyDao;
import com.ft.dao.StudyFistcommentDao;
import com.ft.domain.Fistcomment;
import com.ft.domain.StudyFistcomment;
import com.ft.excepion.BusinessException;
import com.ft.service.IStudyFistcommentService;
import com.ft.utils.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.*;

/**
 * @Author: ft
 * @Date: 2023/01/12/12:31
 * @Description:
 */
@Service
public class StudyFistcommentServiceImpl extends ServiceImpl<StudyFistcommentDao, StudyFistcomment> implements IStudyFistcommentService {
    @Autowired
    private StudyFistcommentDao fistcommentDao;
    @Autowired
    private StudyAnswerDao studyAnswerDao;
    @Autowired
    private StudyDao studyDao;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public int addfistcomment(StudyFistcomment fistcomment) throws IllegalAccessException {
        int i = fistcommentDao.addFistcomment (fistcomment);
        //获取帖子的所有评论id集合
        String commentidList = studyDao.getCommentidList(fistcomment.getBelongpost ());
        //添加评论的id
        if(commentidList.length () > 0 & commentidList != ""){
            commentidList = commentidList +fistcomment.getId ()+",";
        }else {
            commentidList = fistcomment.getId ()+",";
        }
        //获取帖子所有回复数量
        int commentnum = studyDao.getCommentnum (fistcomment.getBelongpost ());
        //更新帖子的所有回复数
        int j = studyDao.updataCommentnum (commentnum+1, fistcomment.getBelongpost ());
        //更新帖子评论id
        int h = studyDao.updataCommentList (commentidList, fistcomment.getBelongpost ());
        if(i == 1 & j == 1 & h == 1){
            //1.将评论id存入缓存
            String id = String.valueOf (fistcomment.getId ());
            redisTemplate.opsForZSet().add("studyfistcommentId",id,0);
            //将评论信息存入缓存
            String postKey1 = "studyfistcomment:"+fistcomment.getId ();
            Map<String, Object> stringObjectMap = ObjectUtils.objectToMap (fistcomment);
            redisTemplate.opsForHash ().putAll (postKey1, stringObjectMap);
            //同步帖子创建时间
            redisTemplate.opsForHash().delete(postKey1,"createTime");
            String time = fistcommentDao.getcreateTime(fistcomment.getId ());
            redisTemplate.opsForHash().put(postKey1,"createTime",time);
            //检查是数据否添加成功
            Long  hashOrderSize = redisTemplate.opsForHash().size (postKey1);
            while (true){
                //结束条件,验证每个字段是否都添加上了
                if(hashOrderSize == StudyFistcomment.total){
                    break;
                }
                if(hashOrderSize != StudyFistcomment.total){
                    //移除key
                    redisTemplate.delete (postKey1);
                    //重新添加
                    Map<String, Object> stringObjectMap1 = ObjectUtils.objectToMap (fistcomment);
                    Set mapkey1 = stringObjectMap1.keySet ();
                    for(Object key : mapkey1){
                        redisTemplate.opsForHash().put(postKey1,key,stringObjectMap.get (key));
                    }
                }
            }
            //更新redis中的帖子评论id缓存字段
            //修改redis中对应字段
            redisTemplate.opsForHash().put("study:"+fistcomment.getBelongpost (),"commentidlist",commentidList);
            redisTemplate.opsForHash().put("study:"+fistcomment.getBelongpost(),"commentnum",commentnum+1);
            return 1;
        }else{
            return 0;
        }
    }

    @Override
    public List<StudyFistcomment> getfistcommentsByPostId(String postId) {
        List list = new ArrayList ();
        String str = (String) redisTemplate.opsForHash ().get ("study:" + postId, "commentidlist");
        String[] splitstr = str.split (",");
        System.out.println (Arrays.toString (splitstr));
        //获取对应的fistcomment数据
        for (int i = 0; i < splitstr.length; i++) {
            Fistcomment fistcomment = new Fistcomment();
            Map entries = redisTemplate.opsForHash ().entries ("studyfistcomment:" + splitstr[i]);
            System.out.println("studyfistcomment:" + splitstr[i] + entries);
            fistcomment.setId ((Long) entries.get("id"));
            fistcomment.setBelongpost ((Long) entries.get("belongpost"));
            fistcomment.setContent ((String) entries.get("content"));
            fistcomment.setCreateTime (Timestamp.valueOf((String) entries.get("createTime")));
            fistcomment.setState ((Integer) entries.get("state"));
            fistcomment.setAnswerIdlist ((String) entries.get("answerIdlist"));
            fistcomment.setCommentUserimg ((String) entries.get("commentUserimg"));
            fistcomment.setCommentUsername ((String)entries.get("commentUsername"));
            fistcomment.setCommentUserid ((Integer) entries.get("commentUserid"));
            list.add(fistcomment);
        }
        return list;
    }

    @Override
    public int deleteFistcomment(Long id) {
        System.out.println("删除的评论id"+id);
        //获取该评论所有的回复id
        String answerIdlist = fistcommentDao.getAnswerIdlist (id);
        String[] answerList = new String[0];
        int i = 0;
        System.out.println("answerIdlist: " + answerIdlist+"数组初始："+answerList.toString () );
        if(answerIdlist != null & answerIdlist.length () > 0) {
            System.out.println ("1");
          answerList = answerIdlist.split(",");
          i = studyAnswerDao.deleteAnswerArray (answerList);
        }
        //获取帖子中包含的评论内容，移除该评论id
        Long studyId = fistcommentDao.getStudyId (id);
        String commentidList = studyDao.getCommentidList (studyId);
        String[] commentlist = commentidList.split (",");
        String T = "";
        for(int j = 0; j  < commentlist.length; j++){
            if(commentlist[j].equals(""+id)){
                continue;
            }
            T += commentlist[j]+",";
        }
        System.out.println ("T:"+T);
        //更新帖子中的评论id集合
        int i2 = studyDao.updataCommentList (T, studyId);
        //更新帖子中的评论回复数量
        int commentnum = studyDao.getCommentnum (studyId);
        int a = commentnum - 1 - answerList.length ;
        System.out.println("回复数量是："+commentnum+"回复内容数组的数量是"+answerList.length+"处理后的回复数据是：" +a );
        System.out.println("这是数组内容"+answerList.toString ());
        int i3 = studyDao.updataCommentnum (a, studyId);
        //删除评论
        int i1 = fistcommentDao.deleteFistComment (id);
        //删除成功的情况,更新缓存
        if (i == answerList.length & i1 == 1 & i2 == 1 & i3 == 1) {
            System.out.println("进入到处理缓存");
            //处理回复的缓存
            for(int j = 0; j < answerList.length; j++) {
                //更新redis中回复hash的数据
                redisTemplate.delete ("studyanswer:"+ answerList[j]);
                //删除回复zet中对应id
                redisTemplate.boundZSetOps("studyanswerId").remove(""+answerList[j]);
            }
            //处理评论的缓存
            redisTemplate.delete ("studyfistcomment:"+ id);
            redisTemplate.boundZSetOps("studyfistcommentId").remove(""+id);
            //处理帖子的缓存
            //更新redis中评论表的用户回复id集合字段
            redisTemplate.opsForHash().put("study:"+studyId,"commentidlist",T);
            //更新帖子回复数
            redisTemplate.opsForHash().put("study:"+studyId,"commentnum", a);
            return  1 ;
        }
        return 0;
    }

    /**
     * 根据
     * @param array
     * @param belongpost
     * @return
     */
    @Override
    public int deleteFistcommentArray(String[] array, Long belongpost) {
        //获取要删除的评论个数
        int num = array.length ;
        //删除的所有回复数
        int T = 0 ;
        //遍历循环，删除该评论的所有回复
        for (int i = 0 ; i < array.length ; i++){
            //删除该评论的所有回复
            T += studyAnswerDao.deleteAnswerArray (fistcommentDao.getAnswerIdlist (Long.valueOf (array[i])).split (","));
        }
        //将用户回复id集合存入帖子表中
        int i1 = studyDao.updataCommentList ("",belongpost);
        //获取帖子回复数量
        int commentnum = studyDao.getCommentnum (belongpost);
        //删除成功的情况
        if( i1 == 1 ){
            System.out.println ("进入删除缓存");
            //更新缓存数据
            for (int j = 0; j < array.length; j++) {
                System.out.println ("评论的id：" + array[j]);
                //删除所有的回复数据
                String[] split = fistcommentDao.getAnswerIdlist (Long.valueOf (array[j])).split (",");
                System.out.println ("split的值是："+split.toString ());
                for(int b = 0; b <split.length; b++){
                    redisTemplate.delete ("studyanswer:"+split[b]);
                    //删除回复zet中对应id
                    redisTemplate.boundZSetOps("studyanswerId").remove(""+split[b]);
                }
                //删除评论hash表
                redisTemplate.delete ("studyfistcomment:"+array[j]);
                //删除评论zet中对应id
                redisTemplate.boundZSetOps("studyfistcommentId").remove(""+array[j]);
            }
            //更新redis中评论表的用户回复id集合字段
            redisTemplate.opsForHash().put("study:"+belongpost,"commentidlist","");
            //更新帖子回复数
            redisTemplate.opsForHash().put("study:"+belongpost,"commentnum",commentnum-num-T);
            int i = fistcommentDao.deletefistcommentArray (array);
            //更新帖子回复量
            int h = studyDao.updataCommentnum (commentnum-num-T, belongpost);
            if(i == num){
                return 1;
            }
            return 0 ;
        }
        return 0;
    }
}
